package app

import (
	"fmt"
	"os"
	"runtime/debug"
	"time"

	"huohuo-compress/backend/model"
	"huohuo-compress/backend/myfile"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

// 实例化
var compressFileList = make([]model.CompressFile, 0)
var compressSession = model.CompressSession{
	Total:    0,
	TodoNum:  0,
	Duration: 0,
}

// SelectDir 设置目标文件夹
func (a *App) SelectDir() (dir string, err error) {
	dir, err = runtime.OpenDirectoryDialog(a.ctx, runtime.OpenDialogOptions{})
	return dir, err
}

// SelectSingleFile 选择单个文件
func (a *App) SelectSingleFile() (file string, err error) {
	file, err = runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{})
	return file, err
}

// 获取应用默认文件夹
func (a *App) GetDefaultDir() string {
	apath, _ := os.Getwd()
	return apath
}

// CompressFileListClear 重置图片列表
func (a *App) CompressFileListClear() {
	compressFileList = compressFileList[0:0]
	compressSession.Total = 0
	compressSession.TodoNum = 0
	compressSession.Duration = 0
	runtime.EventsEmit(a.ctx, "event:compressFileList", compressFileList)
	runtime.EventsEmit(a.ctx, "event:compressSession", compressSession)
	debug.FreeOSMemory()
}

// SelectMultipleFiles 选择多个文件
func (a *App) SelectMultipleFiles() {
	fileList, _ := runtime.OpenMultipleFilesDialog(a.ctx, runtime.OpenDialogOptions{})
	compressFileList = myfile.GetCompressFileListWithSelect(fileList, compressFileList)
	compressSession.Total = len(compressFileList)
	runtime.EventsEmit(a.ctx, "event:compressFileList", compressFileList)
	runtime.EventsEmit(a.ctx, "event:compressSession", compressSession)
}

// CompressImages  按照配置处理图片
func (a *App) CompressImages(c model.CompressFileConfig) (err error) {
	t := time.Now()
	for k, file := range compressFileList {
		file.Status = "process"
		singleTime := time.Now()
		runtime.EventsEmit(a.ctx, "event:fileStateUpdate", file)
		if file.Status == "error" {
			continue
		}
		err = file.CompressImages(c)
		if err != nil {
			fmt.Printf("err: %v \n", err)
			file.Status = "error"
		} else {
			file.Status = "success"
		}
		file.Duration = time.Since(singleTime) / (1000 * 1000)
		runtime.EventsEmit(a.ctx, "event:fileStateUpdate", file)
		compressSession.TodoNum = k + 1
		compressSession.Duration = time.Since(t) / (1000 * 1000)
		runtime.EventsEmit(a.ctx, "event:compressSession", compressSession)
	}
	debug.FreeOSMemory()
	return nil
}
